/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Client_Login.java
 *
 * Created on Jun 12, 2012, 10:48:55 PM
 */
package databaseclient;

/**
 *
 * @author Administrator
 */
import TranSport.*;
import com.sun.corba.se.impl.io.IIOPInputStream;
import com.sun.xml.internal.ws.api.message.Message;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.omg.PortableInterceptor.TRANSPORT_RETRY;
public class Client_Login extends javax.swing.JFrame {

    public Client client;
    public Socket socket;
    public boolean isConnect;
    public ObjectInputStream input ;
    public ObjectOutputStream output;
    
    public Transport tran;
    public Vector<StringDataBase> stringDatabase;
    /** Creates new form Client_Login */
    public Client_Login() {
        initComponents();
        isConnect = false;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        titledBorder1 = javax.swing.BorderFactory.createTitledBorder("");
        jLabel1 = new javax.swing.JLabel();
        Text_IpServer = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        Text_Port = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        Text_User = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        Text_Pass = new javax.swing.JTextField();
        bt_Connect = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        bt_disconnect = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login");
        setModalExclusionType(java.awt.Dialog.ModalExclusionType.TOOLKIT_EXCLUDE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("IP Server");

        Text_IpServer.setText("localhost");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Port ");

        Text_Port.setFont(new java.awt.Font("Tahoma", 0, 12));
        Text_Port.setText("2003");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel3.setText("UserName");

        Text_User.setText("anhvien");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel4.setText("Password");

        bt_Connect.setText("Connect");
        bt_Connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_ConnectActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18));
        jLabel5.setForeground(new java.awt.Color(51, 51, 255));
        jLabel5.setText("Login to server");

        bt_disconnect.setText("Disconnect");
        bt_disconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_disconnectActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(Text_Pass)
                    .addComponent(Text_User)
                    .addComponent(Text_Port)
                    .addComponent(Text_IpServer, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(72, 72, 72))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(123, Short.MAX_VALUE)
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(81, 81, 81))
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(bt_Connect, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(bt_disconnect, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Text_IpServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(Text_Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(Text_User, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(Text_Pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_Connect)
                    .addComponent(bt_disconnect))
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void bt_ConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_ConnectActionPerformed
// TODO add your handling code here:
    if(!isConnect)
    {
        isConnect = true;
        
        Login log = new Login();
        try
        {
            log.UserName = this.Text_User.getText();
            log.Password = this.Text_Pass.getText();
            log.Ip = this.Text_IpServer.getText();
            log.Port = Integer.parseInt(this.Text_Port.getText());
        }catch(Exception e)
        {
            JOptionPane.showMessageDialog(this, "Loi tai gia tri port ko phai kieu int");
            Stop_connect();
            return ;
        }
        try
        {
        socket = new Socket(log.Ip,log.Port);
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, "Loi khi connect toi server : "+ex.getMessage());
            Stop_connect();
            return;
        }
        
        // tao dong doc va truyen du lieu 
        try
        {
            output = new ObjectOutputStream(socket.getOutputStream());
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, "Loi tao cac dong nhap xuat du lieu : "+ex.getMessage());
           Stop_connect();
            return ;
        }
        
        // guoi yeu cau connect den server 
        tran = new Transport();
        tran.login.Copy(log);
        tran.Mesage = "Login";
        try
        {
        output.writeObject(tran);
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, "Loi trong qua trinh dua du lieu len server : "+ex.getMessage());
            Stop_connect();
            return;
        }
        // doc du lieu tra ve tu server 
        try
        {
            input = new ObjectInputStream(socket.getInputStream());
            tran = (Transport)input.readObject();
            
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(this, "Loi Trong qua trinh doc du lieu tu server : "+ex.getMessage());
            Stop_connect();
            return;
        }
        
        if(tran != null)
        {
            if(tran.Mesage.equalsIgnoreCase("LoginOK"))
            {
                stringDatabase = new Vector<StringDataBase>();
                stringDatabase = tran.stringDataBase;
                client = new Client();
                client.output = output;
                client.input = input;
                client.stringDataBase = stringDatabase;
                client.tran = tran;
                client.setVisible(true);
                client.Test();
            }
            else if (tran.Mesage.equalsIgnoreCase("LoginError"))
            {
                JOptionPane.showMessageDialog(this, "Loi connect toi server : "+tran.errorMessage);
                Stop_connect();
                return;
            }
        }
        
    }
   
    
}//GEN-LAST:event_bt_ConnectActionPerformed

private void bt_disconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_disconnectActionPerformed
// TODO add your handling code here:
    
    
    Stop_connect();
    
}//GEN-LAST:event_bt_disconnectActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client_Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Client_Login().setVisible(true);
            }
        });
    }
    public void Stop_connect()
    {
        isConnect = false;
    socket = null;
    if(client != null)
    {
        client.setVisible(false);
        client = null;
    }
    input = null;
    output = null;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField Text_IpServer;
    private javax.swing.JTextField Text_Pass;
    private javax.swing.JTextField Text_Port;
    private javax.swing.JTextField Text_User;
    private javax.swing.JButton bt_Connect;
    private javax.swing.JButton bt_disconnect;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.border.TitledBorder titledBorder1;
    // End of variables declaration//GEN-END:variables
}
